package cz.schovjan.proj.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import cz.schovjan.proj.dao.IUserDao;
import cz.schovjan.proj.entity.UserEntity;

/**
 * Implementace IUserDao
 * @author schovjan
 * 
 */
@Repository
public class JpaUserDao implements IUserDao {

	private static final String FIND_ALL = "select u from UserEntity as u";
	private static final String NICK_PASSWORD = "select u from UserEntity as u where u.nick = :nick and u.password = :pass";

	@PersistenceContext
	private EntityManager em;
	
	
	@Override
	@SuppressWarnings("unchecked")
	public List<UserEntity> findAll() {
		return em.createQuery(FIND_ALL).getResultList();
	}

	
	@Override
	public UserEntity findUser(String nick, String password) {
		UserEntity result = null;
		Query q = em.createQuery(NICK_PASSWORD);
		q.setParameter("nick", nick);
		q.setParameter("pass", password);
		if (!q.getResultList().isEmpty()) {
			result = (UserEntity) q.getResultList().get(0);
		}
		
		return result;
	}
	
	
	@Override
	public void add(UserEntity ue) {
		em.persist(ue);
	}
	
	
	@Override
	public UserEntity find(String nick) {
		return em.find(UserEntity.class, nick);
	}
	
	
	@Override
	public void delete(String nick) {
		UserEntity ue = find(nick);
		if (ue != null) {
			em.remove(ue);
		}
	}
	
}
